package com.love.netty.demo.handler;

import com.love.netty.core.packet.Packet;
import com.love.netty.core.packet.PacketCodeC;
import com.love.netty.core.packet.request.LoginRequestPacket;
import com.love.netty.core.packet.response.LoginResponsePacket;
import com.love.netty.core.packet.response.MessageResponsePacket;
import com.love.netty.util.LoginUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName: ClientHandler
 * @Description:
 * @Author: wuj
 * @Date: 2021-06-23 15:08
 **/
public class ClientHandler extends ChannelInboundHandlerAdapter {

    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println(new Date() + " 客户端开始登录");

        // 创建登录对象
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(UUID.randomUUID().toString());
        loginRequestPacket.setUserName("flash");
        loginRequestPacket.setPassword("pwd");

        // 编码
        //ByteBuf buffer = PacketCodeC.getInstance().encode(ctx.alloc().buffer(), loginRequestPacket);

        // 写数据
        //ctx.channel().writeAndFlush(buffer);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf byteBuf = (ByteBuf) msg;

        Packet packet = PacketCodeC.getInstance().decode(byteBuf);

        if (packet instanceof LoginResponsePacket) {
            LoginResponsePacket loginResponsePacket = (LoginResponsePacket) packet;

            if (loginResponsePacket.isSuccess()) {
                LoginUtils.markAsLogin(ctx.channel());
                System.out.println(sdf.format(new Date()) + ": 客户端登录成功");
            } else {
                System.out.println(sdf.format(new Date())+ ": 客户端登录失败，原因：" + loginResponsePacket.getReason());
            }
        }else if (packet instanceof MessageResponsePacket) {
            MessageResponsePacket messageResponsePacket = (MessageResponsePacket) packet;
            System.out.println(sdf.format(new Date()) + ": 收到服务端的消息: " + messageResponsePacket.getMessage());
        }
    }
}
